package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.common.WmUserThrealLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import org.springframework.beans.BeanUtils;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Resource
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Resource
    private WmMaterialMapper wmMaterialMapper;
    @Resource
    private WmNewsAutoScanService wmNewsAutoScanService;
    @Resource
    private KafkaTemplate<String, String> kafkaTemplate;

    @Resource
    private WmNewsTaskService wmNewsTaskService;
    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        //1.检查参数
        if (null == dto) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //分页参数检查
        dto.checkParam();

        //2.分页条件查询
        Page page = new Page(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
        //状态精确查询
        if (null != dto.getStatus()) {
            wrapper.eq(WmNews::getStatus, dto.getStatus());
        }

        //频道精确查询
        if (null != dto.getChannelId()) {
            wrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }

        //时间范围查询
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null) {
            wrapper.ge(WmNews::getPublishTime, dto.getBeginPubDate()).le(WmNews::getPublishTime, dto.getEndPubDate());
        }

        //关键字模糊查询
        if (!StringUtils.isBlank(dto.getKeyword())) {
            wrapper.like(WmNews::getTitle, dto.getKeyword());
        }

        //查询当前登录用户的文章
        wrapper.ge(WmNews::getUserId, WmUserThrealLocalUtil.get());

        //发布时间倒序查询
        wrapper.orderByDesc(WmNews::getPublishTime);

        //3.结果返回
        Page pages = pageMaps(page, wrapper);
        ResponseResult result = new PageResponseResult((int) pages.getCurrent(), (int) pages.getSize(), (int) pages.getTotal());
        result.setData(pages.getRecords());
        return result;
    }

    @Override
    public ResponseResult submitNews(WmNewsDto dto) {
        //1.检查参数
        if (dto == null || StringUtils.isEmpty(dto.getContent())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.保存或修改文章
        WmNews wmNews = saveOrUpdateNews(dto);

        //3.如果状态为0，则保存为草稿
        if (dto.getStatus().equals(WmNews.Status.NORMAL.getCode())) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        //从内容中提取图片
        List<String> materials = ectractUrlInfo(dto.getContent());

        //4.保存文章内容图片与素材的关系
        saveRelativeInfoForContent(materials, wmNews.getId());

        //5.保存文章封面图片与素材的关系
        saveRelativeInfoForCover(dto, wmNews, materials);
        //审核文章
//        wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
        wmNewsTaskService.addWmNewsToTask(wmNews);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }

    /**
     * 文章上下架
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downorup(WmNewsDto dto) {
        if (dto.getId() == null) {
            return ResponseResult.errorResult(501, "文章ID不可缺少");
        }
        WmNews wmNews = getById(dto.getId());
        if (null == wmNews) {
            return ResponseResult.errorResult(1002, "文章不存在");
        }
        if (wmNews.getStatus() != 9) {
            return ResponseResult.errorResult(501, "当前文章不是发布状态,不能上下架");
        }
        BeanUtils.copyProperties(dto, wmNews);
        updateById(wmNews);
        kafkaTemplate.send("enable", wmNews.getArticleId() + "&" + dto.getEnable());
        return ResponseResult.okResult("操作成功");
    }

    private void saveRelativeInfoForCover(WmNewsDto dto, WmNews wmNews, List<String> materials) {
        //判断封面是否为自动，如果是自动则按照产品经历的规则进行图片抽取（内容中抽取图片）
        if (dto.getType() == -1) {
            dto.setImages(new ArrayList<>());
            //抽取图片
            //如果内容中的图片的数量大于3多图
            if (materials.size() > 3) {
                dto.getImages().addAll(materials.stream().limit(3).collect(Collectors.toList()));
                wmNews.setType((short) 3);
            } else if (materials.size() >= 1) {
                dto.getImages().addAll(materials.stream().limit(1).collect(Collectors.toList()));
                wmNews.setType((short) 1);
            } else {
                wmNews.setType((short) 0);
            }
            //更新自动的文章的类型
            updateById(wmNews);
        }
        //如果不是自动 则直接保存关系即可
        List<String> urlList = dto.getImages();
        if (null != urlList && urlList.size() > 0) {
            urlList = urlList.stream().distinct().collect(Collectors.toList());
            //通过url地址查询素材的id
            List<WmMaterial> wmMaterialList = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, urlList));
            List<Integer> idsList = wmMaterialList.stream().map(wmMaterial -> wmMaterial.getId()).collect(Collectors.toList());
            //判断我们查询到的数据和ids的数据是否一致 如果不一致则抛出异常
            if (urlList.size() != idsList.size()) {
                throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
            }
            //批量插入关系数据
            wmNewsMaterialMapper.bachInert(idsList, wmNews.getId(), WemediaConstants.WM_COVER_REFERENCE);
        }
    }

    private void saveRelativeInfoForContent(List<String> materials, Integer id) {
        //去重
        if (null != materials && materials.size() > 0) {
            materials = materials.stream().distinct().collect(Collectors.toList());
            //通过url地址查询素材的id
            List<WmMaterial> wmMaterialList = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, materials));

            List<Integer> idsList = wmMaterialList.stream().map(wmMaterial -> wmMaterial.getId()).collect(Collectors.toList());
            //判断我们查询到的数据和ids的数据是否一致 如果不一致则抛出异常
            if (materials.size() != idsList.size()) {
                throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
            }
            //批量插入关系数据
            wmNewsMaterialMapper.bachInert(idsList, id, WemediaConstants.CANCEL_COLLECT_MATERIAL);
        }
    }

    private List<String> ectractUrlInfo(String content) {
        ArrayList<String> list = new ArrayList<>();
        if (StringUtils.isNotBlank(content)) {
            for (Map map : JSONObject.parseArray(content, Map.class)) {
                if (map.get("type").equals("image")) {
                    list.add(map.get("value").toString());
                }
            }
        }
        return list;
    }

    private WmNews saveOrUpdateNews(WmNewsDto dto) {
        //把dto中的数据拷贝到pojo
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
        //处理拷贝不成功的属性
        if (dto.getType() == -1) {
            //-1表示自动，数据库定义为无符号数
            wmNews.setType(null);
        }
        //处理图片
        if (null != dto.getImages() && dto.getImages().size() > 0) {
            wmNews.setImages(StringUtils.join(dto.getImages(), ","));
        }
        //补齐一些基本的字段
        wmNews.setCreatedTime(new Date());
        wmNews.setUserId(WmUserThrealLocalUtil.get().intValue());
        wmNews.setEnable((short) 1);
        wmNews.setSubmitedTime(new Date());
        //判断文章是否有id如果没有 则新增
        if (null == wmNews.getId()) {
            save(wmNews);
        } else {
            //如果有id 则先删除文章和素材之间的关系 然后修改文章
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, dto.getId()));
            updateById(wmNews);
        }
        return wmNews;
    }
}
